<template>
  <d2-container>
    <template slot="header">
      <el-button size="small" type="primary" @click="showDialog(null)">新增文章</el-button>
    </template>
    <el-form :inline="true" :model="searchForm">
      <el-form-item label="文章名称">
        <el-input size="small" v-model="searchForm.name" placeholder="文章名称"></el-input>
      </el-form-item>
      <el-form-item label="文章类型">
        <el-select clearable v-model="searchForm.articleType" placeholder="请选择文章类型">
          <el-option label="HTML:富文本" value="HTML"></el-option>
          <el-option label="TEMPLATE:相册模板" value="TEMPLATE"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button size="small" type="plain" @click="articleList()">查询</el-button>
      </el-form-item>
    </el-form>
    <el-table v-loading="tableLoading" :data="tags" style="width: 100%;" :stripe="true" :border="true">
      <el-table-column prop="id" label="文章ID" width="80">
      </el-table-column>
      <el-table-column prop="title" label="标题" width="180">
      </el-table-column>
      <el-table-column prop="articleType" label="文章类型" width="180">
      </el-table-column>
      <el-table-column prop="summary" label="概要" width="180">
      </el-table-column>
      <el-table-column prop="isSubmit" label="是否收录" width="180">
        <template slot-scope="scope">
          <span>{{scope.row.isSubmit==1?'已收录':'未收录'}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="submitTime" label="收录时间" width="180">
      </el-table-column>
      <el-table-column prop="coverPic" label="封面图" width="180">
        <template slot-scope="scope">
          <el-image :preview-src-list="[scope.row.coverPic]" style="width: 100px; height: 100px" :src="scope.row.coverPic" fit="fill"></el-image>
        </template>
      </el-table-column>
      <el-table-column prop="action" label="操作" width="180">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="preview(scope.row)">预览</el-button>
          <el-button type="text" size="small" @click="submitPages(scope.row)">提交收录</el-button>
          <el-button type="text" size="small" @click="showDialog(scope.row)">编辑</el-button>
          <el-button type="text" size="small" @click="deleteTag(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog v-loading="editLoading" :title="dialogTitle" :visible.sync="dialogVisible">
      <el-form v-if="dialogVisible" :model="form" :rules="rules" ref="editForm">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="文章概要" prop="summary">
          <el-input v-model="form.summary" type="textarea" :rows="2" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="封面图" prop="coverPic">
          <el-input v-show="false" v-model="form.coverPic"></el-input>
          <el-upload drag action="" :on-change="getFile" :limit="2" :file-list="fileList" list-type="picture" :auto-upload="false">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
              将文件拖到此处，或<em>点击上传</em>
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="文章类型"  prop="articleType">
          <el-select clearable v-model="form.articleType" placeholder="请选择文章类型">
            <el-option label="HTML:富文本" value="HTML"></el-option>
            <el-option label="TEMPLATE:相册模板" value="TEMPLATE"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-show="form.articleType=='HTML'" label="" prop="content">
          <d2-quill  v-show="form.articleType=='HTML'" style="min-height: 200px; margin-bottom: 20px;" v-model="form.content" />
        </el-form-item>
        <el-form-item v-if="form.articleType!='HTML'" label="" prop="content">
          <el-input type="textarea" rows="10" style="min-height: 200px; margin-bottom: 20px;" v-model="form.content" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submit()">确 定</el-button>
      </span>
    </el-dialog>
    <template slot="footer">
      <p align="right">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPageInfo.current" :page-sizes="pageSizeOptions" :page-size="currentPageInfo.size" layout="total, sizes, prev, pager, next, jumper" :total="currentPageInfo.total">
        </el-pagination>
      </p>
    </template>
    <el-dialog v-if="previewDialogVisible" :title="'预览-'+currentArticle.title" :visible.sync="previewDialogVisible">
      <div v-if="previewDialogVisible" v-html="currentArticle.content"></div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="previewDialogVisible = false">关 闭</el-button>
      </span>
    </el-dialog>
  </d2-container>
</template>

<script>
import dayjs from 'dayjs'
import api from "@/api";
export default {
  data () {
    return {
      fileList: [],
      searchForm: {
      },
      previewDialogVisible: false,
      tableLoading: false,
      currentPageInfo: {
        current: 1,
        size: 10,
        total: 0
      },
      pageSizeOptions: [5, 10, 20, 40],
      editLoading: false,
      formLabelWidth: "120px",
      form: {
        articleType: 'HTML'
      },
      tags: [],
      currentArticle: null,
      dialogVisible: false,
      rules: {
        title: [
          { required: true, message: "请输入标题", trigger: "blur" },
          { min: 0, max: 32, message: "长度在 0 到 64 个字符", trigger: "blur" }
        ],
        articleType: [
          { required: true, message: "请选择文章类型", trigger: "blur" }
        ],
        content: [
          { required: true, message: "请输入内容", trigger: "blur" }
        ],
        summary: [
          { required: true, message: "请输入概要", trigger: "blur" },
          {
            min: 0,
            max: 256,
            message: "长度在 0 到 512 个字符",
            trigger: "blur"
          }
        ]
      }
    };
  },
  computed: {
    dialogTitle () {
      return this.currentArticle == null
        ? "新增文章"
        : "编辑文章 - " + this.currentArticle.title;
    },
    isNew () {
      return this.currentArticle == null;
    }
  },
  methods: {
    async submitPages (article) {
      this.tableLoading = true;
      var res = await api.service.post("/backManage/submit/pages?id=" + article.id).catch(function(error) { });
      if (res) {
        this.$message({
          message: "提交成功！",
          type: "success"
        });
      }
      this.articleList();
      this.tableLoading = false;
    },
    preview (article) {
      this.currentArticle = article
      this.previewDialogVisible = true
    },
    getFile (file, fileList) {
      if (file.raw.type != "image/jpeg" && file.raw.type != "image/png" && file.raw.type != "image/gif") {
        this.$message({
          message: "仅允许上传jpg、png格式的图片！",
          type: "error"
        });
        this.form.coverPic = "";
        this.$nextTick(() => {
          this.fileList = [];
        });
        return;
      }
      this.getBase64(file.raw).then(res => {
        this.$nextTick(() => {
          this.fileList = [{ name: "", url: res }];
          this.form.coverPic = res;
        });
      });
    },
    getBase64 (file) {
      return new Promise(function(resolve, reject) {
        let reader = new FileReader();
        let imgResult = "";
        reader.readAsDataURL(file);
        reader.onload = function() {
          imgResult = reader.result;
        };
        reader.onerror = function(error) {
          reject(error);
        };
        reader.onloadend = function() {
          resolve(imgResult);
        };
      });
    },
    handleSizeChange (val) {
      this.currentPageInfo.size = val;
      this.currentPageInfo.current = 1;
      this.articleList();
    },
    handleCurrentChange (val) {
      this.currentPageInfo.current = val;
      this.articleList();
    },
    showDialog (currentArticle) {
      this.fileList = []
      this.currentArticle = currentArticle;
      this.form = currentArticle ? {
        ...JSON.parse(JSON.stringify(currentArticle))
      } : {
        articleType: 'HTML'
        };
      if (currentArticle) {
        this.fileList = [{ name: "", url: currentArticle.coverPic }];
      }
      this.dialogVisible = true;
    },
    deleteTag (article) {
      this.$confirm('确定要删除"' + article.title + '"文章吗？', "删除标签", {
        type: "warning"
      }).then(async _ => {
        var res = await api.service.delete("/backManage/articles", {
          params: {
            ids: article.id
          }
        }).catch(function(error) { });
        if (res) {
          this.$message({
            message: "删除成功！",
            type: "success"
          });
          this.articleList();
        }
      });
    },
    submit () {
      this.$refs.editForm.validate(async valid => {
        if (valid) {
          this.editLoading = true;
          var res = await api.service.post("/backManage/article", this.form).catch(function(error) { });
          if (res) {
            this.$message({
              message: this.isNew ? "新增成功！" : "修改成功！",
              type: "success"
            });
            this.dialogVisible = false;
            this.articleList();
          }
          this.editLoading = false;
        }
      });
    },
    async articleList () {
      this.tableLoading = true;
      var data = await api.service.get("/backManage/articles", {
        params: {
          name: this.searchForm.name,
          articleType: this.searchForm.articleType,
          currentPage: this.currentPageInfo.current,
          pageSize: this.currentPageInfo.size
        }
      }).catch(function(error) { });
      this.currentPageInfo = data;
      this.tags = data.records;
      this.tableLoading = false;
    }
  },
  created () {
    this.articleList();
  }
};
</script>
